<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="username"><button onclick="login()">登录聊天室</button>
给<input type="text" id="to_user">发:<input type="text" id="msg"><button onclick="send_msg()">发送</button>
<div id="chat_list" style="width: 500px;height: 500px"></div>
<script type="application/javascript">
    var ws = null;
    function login() {
        var username = document.getElementById("username").value;
        ws = new WebSocket("ws://127.0.0.1:9527/dan/"+username);
        ws.onopen = function () {
          console.log("123")
        };
        ws.onmessage = function (data) {
            console.log(data.data);
            var recv_msg = JSON.parse(data.data);
            var ptag = document.createElement("p");
            ptag.innerText = recv_msg.from_user + ": " + recv_msg.msg;
            document.getElementById("chat_list").appendChild(ptag);
        };
        ws.onclose = function () {
          window.location.reload();
        };
    }
    function send_msg() {
        var to_user = document.getElementById("to_user").value;
        var msg = document.getElementById("msg").value;
        var msg_dict = {
          "to_user":to_user,
          "msg":msg
        };
        msg_str = JSON.stringify(msg_dict);
        ws.send(msg_str)
    }

</script>
</body>
</html>